/*
 * @Description: 新建项目
 * @Author: Mr.Wen
 * @Version: v1.0.0
 * @Date: 2021-12-08 15:37:07
 * @LastEditors: Mr.Wen - 文先生
 * @LastEditTime: 2024-01-10 15:38:31
 */

'use strict';

import readline from 'readline';
import copydir from 'copy-dir';
import path from 'path';
import fs from 'fs';

const resolvePath = _dir => path.resolve(process.cwd(), _dir);
const replaceAll = (str, s1, s2) => str.replace(new RegExp(s1, 'gm'), s2);

const readSyncBy = tips => {
  const newTips = tips || '> ';

  return new Promise(resolve => {
    const rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout,
    });

    rl.question(newTips, answer => {
      rl.close();
      resolve(answer.trim());
    });
  });
};

// 判断项目是否存在
const isProjectFun = name => new Promise(resolve => {
  let isNext = false;
  const projectNamePath = resolvePath(`${process.cwd()}/src/views/${name}`);

  if (!fs.existsSync(projectNamePath)) {
    fs.mkdirSync(projectNamePath);
    isNext = true;
  }
  resolve(isNext);
});

readSyncBy('请输入项目中文名称（如:文先生）:').then(ChineseName => {
  if (!/^[\u4e00-\u9fa5]+$/.test(ChineseName)) {
    console.log('\x1B[31m%s\x1B[0m', '请输入正确项目名称【中文】');
    return;
  }
  readSyncBy('Please enter the English name of the project(eg:MrWen):').then(EnglishName => {
    if (!/^[a-z-A-Z]+$/.test(EnglishName)) {
      console.log('\x1B[31m%s\x1B[0m', 'Please enter the correct project name[English]');
      return;
    }
    isProjectFun(EnglishName).then(isNext => {
      if (isNext) {
        copydir(resolvePath(`${process.cwd()}/public/templateProject`), resolvePath(`${process.cwd()}/src/views/${EnglishName}`), error => {
          if (!error) {

            fs.writeFileSync(resolvePath(`${process.cwd()}/src/views/${EnglishName}/README.md`), `# ${ChineseName}`);

            fs.readFile(resolvePath(`${process.cwd()}/package.json`), 'utf-8', (err, data) => {
              if (err) console.log('\x1B[31m%s\x1B[0m', err);
              const packageJSON = JSON.parse(data);
              packageJSON.scripts[`dev:${EnglishName}`] = `cross-env RUN_PROJECT=${EnglishName} cross-env PROJECT_NAME=${ChineseName} npm run serve:dev`;
              packageJSON.scripts[`build:${EnglishName}`] = `cross-env RUN_PROJECT=${EnglishName} cross-env PROJECT_NAME=${ChineseName} npm run build:prod`;

              fs.writeFileSync(resolvePath(`${process.cwd()}/package.json`), JSON.stringify(packageJSON, null, 2));
            });

            fs.readFile(resolvePath(`${process.cwd()}/src/views/${EnglishName}/views/Main/Main.jsx`), 'utf8', (err, data) => {
              if (err) console.log('\x1B[31m%s\x1B[0m', err);
              const newData1 = replaceAll(data, 'N', EnglishName);
              fs.writeFileSync(resolvePath(`${process.cwd()}/src/views/${EnglishName}/views/Main/Main.jsx`), newData1);
            });

            console.log('\x1B[32m%s\x1B[0m', `恭喜您，'${ChineseName}'项目创建成功!`);
          } else {
            console.log('\x1B[31m%s\x1B[0m', error);
          }
        });
      } else {
        console.log('\x1B[31m%s\x1B[0m', `对不起，你创建的'${ChineseName}'项目已存在!`);
      }
    });
  });
});
